package org.spruice;

import org.springframework.context.support.GenericApplicationContext;

import java.util.Map;

/**
 * User: mrettig
 * Date: Feb 7, 2009
 * Time: 4:38:08 PM
 */
public class ModuleContext {
    private GenericApplicationContext _springContext;

    public ModuleContext() {
        _springContext = new GenericApplicationContext();
    }

    public ModuleContext(GenericApplicationContext _springContext) {
        this._springContext = _springContext;
    }

    public <T> T get(String s) {
        return (T) _springContext.getBean(s);
    }

    public GenericApplicationContext getSpringContext() {
        return _springContext;
    }

    public void start() {
        _springContext.refresh();
        _springContext.start();
    }

    public void stop() {
        _springContext.stop();
    }

    public void destroy() {
        _springContext.destroy();
    }

    public <T> T get(Class<T> type) {
        Map m = _springContext.getBeansOfType(type);
        if (m.size() == 1) {
            return (T) m.values().iterator().next();
        }
        if (m.size() == 0) {
            return null;
        }
        throw new RuntimeException(m.size() + " items found for: " + type);
    }

    public <T> Map<String, T> getBeansOfType(Class<T> type) {
        return _springContext.getBeansOfType(type);
    }
}
